Event.observe(window, 'load', function() {

	var collection = document.getElementsByClassName('wg-comm_rights');
	for ( var i=0; i<collection.length; i++ ) {
		crw_bind(collection[i]);
	}

//	document.getElementsByClassName('wg-comm_rights').each(function(widget) {
//		crw_bind(widget)
//	});
});

function crw_bind(widget) {
	var add = widget.getElementsByClassName('add-')['0'];
	Event.observe(add, 'click',  crw_edit_settings.bindAsEventListener(widget, widget, add.href));
}

function show_selects_ie( is_show ) {
	if (!Prototype.Browser.IE) return;
	if (is_show) {
		// показать все селекты
		$A(document.getElementsByTagName("select")).each(function(elt) { $(elt).show(); });
	} else {
		// скрыть все селекты
		$A(document.getElementsByTagName("select")).each(function(elt) { $(elt).hide(); });
	}
}


function crw_edit_settings(event, widget, url) {
	Event.stop(event);
	//this.visualEffect('highlight', {duration:1.5});

	obj = this;
	var cp = new cpaint();
	//cp.set_transfer_mode('POST');
	cp.call(
		url,
		'ajax_settings_form',
		function (result) {
			if (result.ajaxResponse['0'].data) {
				var popup = $('popup');

				popup.innerHTML = result.ajaxResponse['0'].data;
				popup.show();
				show_selects_ie(false);

				var form = popup.getElementsByTagName('form')['0'];

				Event.observe(
					popup.getElementsByClassName('cancel-')['0'],
					'click',
					function (event) {
						popup.toggle();
						show_selects_ie(true);
						Event.stop(event);
					}
				);

				var elementsByTag = form.getElementsByTagName("input");
				var elements = new Array();

				for ( var i=0; i<elementsByTag.length; i++ ) {
					elements.push(elementsByTag[i]);
				}

				Event.observe(
					popup.getElementsByClassName('submit-')['0'],
					'click',
					function (event) {
						Event.stop(event);
						//cp.set_transfer_mode(form.method);
						cp.set_response_type('JSON');
						cp.call(
							form.action,
							'ajax_settings_submit',
							function (result) {
								var errors = result.data;
								if (errors) {
									// assign error messages to fields error holders
									for(var name in errors) {
										if (name != 'toJSONString' /* omit cpain method */) {
											$('_' + name).getElementsByClassName('errormsg-')[0].style.display = "block";
											$('_' + name).getElementsByClassName('errormsg-')[0].innerHTML = errors[name];
										}
									}
								} else {
									obj.removeClassName('selected-');

									// показать все селекты
									$A(document.getElementsByTagName("select")).each(function(elt) { $(elt).show(); });

									popup.toggle();
									show_selects_ie(true);
								}
							},
							Form.serializeElements(elements)
						);
					}
				);
			} else {
				obj.addClassName('error-');
			}
		}
	);
}


